import { createApp } from "vue";
import { createPinia } from "pinia";

import App from "./App.vue";
import router from "./router";

import naive from "naive-ui";

import "./assets/main.css";

import axios from "axios";

import { isPlainObject } from "lodash";

import persistedstate from "pinia-plugin-persistedstate";
import { useUserInfo } from "@/stores/user.js";

const app = createApp(App);
app.use(naive);

app.use(createPinia().use(persistedstate));
app.use(router);

const store = useUserInfo();

axios.defaults.baseURL = "/api";
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  if (!config.noToken) {
    config.headers.Token = store.token;
  }
  // 在发送请求之前做些什么
  return config;
});

// 添加响应拦截器
axios.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    if (isPlainObject(response.data) && response.data.code === 200) {
      return response;
    } else {
      console.log("response", response);
      alert(response.data.message);
      if (response.data.code == "401" || response.data.code == "420") {
        console.log(111);
        store.setToken("");
        router.push("/login");
      }
    }
    return Promise.reject(`response data value is "${response.data}"`);
  },
  function (error) {
    // console.log(error);
    if (error.response) {
      const { status, statusText, data } = error.response;
      if (status === 401) {
        alert("未登录");
      } else if (isPlainObject(data)) {
        alert(data.msg);
      } else {
        alert(statusText);
      }
    } else {
      alert(error.message);
    }
    // 对响应错误做点什么;
    return Promise.reject(error);
  }
);

app.mount("#app");
